package com.zut.chat.service;

import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.zut.chat.entity.SysUser;
import com.zut.chat.mapper.SysUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

import static com.zut.chat.entity.table.SysUserTableDef.SYS_USER;

/**
 * 后台管理员用户服务
 */
@Slf4j
@Service
public class SysUserService extends ServiceImpl<SysUserMapper, SysUser> {

    private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    /**
     * 管理员登录验证
     */
    public SysUser login(String username, String password, String loginIp) {
        // 根据用户名查找管理员
        SysUser sysUser = getOne(QueryWrapper.create()
                .where(SYS_USER.USERNAME.eq(username))
                .and(SYS_USER.STATUS.eq(1))); // 只查询启用状态的用户

        if (sysUser == null) {
            log.warn("管理员登录失败：用户名不存在或已禁用 - {}", username);
            return null;
        }
        System.out.println(passwordEncoder.encode("yxq666"));

        // 验证密码
        if (!passwordEncoder.matches(password, sysUser.getPassword())) {
            log.warn("管理员登录失败：密码错误 - {}", username);
            return null;
        }

        // 更新最后登录时间和IP
        sysUser.setLastLoginTime(LocalDateTime.now());
        sysUser.setLastLoginIp(loginIp);
        updateById(sysUser);

        log.info("管理员登录成功 - 用户名: {}, IP: {}", username, loginIp);
        return sysUser;
    }

    /**
     * 根据用户名查找管理员
     */
    public SysUser findByUsername(String username) {
        return getOne(QueryWrapper.create()
                .where(SYS_USER.USERNAME.eq(username))
                .and(SYS_USER.STATUS.eq(1)));
    }

    /**
     * 创建管理员账号
     */
    public boolean createAdmin(String username, String password, String realName) {
        try {
            SysUser sysUser = SysUser.builder()
                    .username(username)
                    .password(passwordEncoder.encode(password))
                    .realName(realName)
                    .status(1)
                    .createTime(LocalDateTime.now())
                    .updateTime(LocalDateTime.now())
                    .build();

            return save(sysUser);
        } catch (Exception e) {
            log.error("创建管理员账号失败", e);
            return false;
        }
    }

    /**
     * 修改密码
     */
    public boolean changePassword(Long userId, String newPassword) {
        try {
            SysUser sysUser = getById(userId);
            if (sysUser != null) {
                sysUser.setPassword(passwordEncoder.encode(newPassword));
                sysUser.setUpdateTime(LocalDateTime.now());
                return updateById(sysUser);
            }
            return false;
        } catch (Exception e) {
            log.error("修改密码失败", e);
            return false;
        }
    }
}
